﻿namespace VisualSVN.Core.Licensing
{
    using System;

    public class Base32Encoder
    {
        private static uint Bits16(uint number16, int from, int to)
        {
            return ((number16 >> to) & (((uint) Math.Pow(2.0, (double) (from - to))) - 1));
        }

        private static string ConvertToNumber(byte[] longNumber, byte base2)
        {
            string str = string.Empty;
            for (int i = 0; i < (longNumber.Length * 8); i += base2)
            {
                uint num2 = longNumber[i / 8];
                if (((i % 8) > (8 - base2)) && ((i / 8) < (longNumber.Length - 1)))
                {
                    num2 += (uint) (longNumber[(i / 8) + 1] << 8);
                }
                byte b = (byte) Bits16(num2, (i % 8) + base2, i % 8);
                str = ValToDigit(b) + str;
            }
            return str;
        }

        public static string Encode(byte[] data)
        {
            return ConvertToNumber(data, 5);
        }

        private static char ValToDigit(byte b)
        {
            if (b <= 9)
            {
                return (char) (b + 0x30);
            }
            return (char) ((b - 10) + 0x61);
        }
    }
}

